<?php

/**
 * 自动生成 MerWxChatService
 * 
 * Apps/Common/Service/MerWxChatService.class.php
 * ryadmin @ 2015-07-11
 */
namespace Common\Service;

class MerWxChatService {
  private static $instance;
  public static function instance() {
    if (self::$instance == null) {
      $instance = new MerWxChatService ();
    }
    return $instance;
  }
  function create($mer_id, $user, $openid) {
    $MerUserOpenid = M ( 'MerUserOpenid' );
    $ret = $MerUserOpenid->where ( array (
        "user_id" => $user,
        "last_op_time" => array (
            'lt',
            date ( 'Y-m-d H:i:s', strtotime ( '+23 hour' ) ) 
        ) 
    ) )
      ->find ();
    if (empty ( $ret )) {
      return ajax_arr ( '对不起对方未在24小时内和服务号沟通过，您无法和他交流', FALSE );
    } else {
      $MerWxChat = M ( 'MerWxChat' );
      $to = $ret ["openid"];
      $res = $MerWxChat->where ( array (
          "mer_id" => $mer_id,
          "_string" => "( from_openid = '$to' or to_openid = '$openid' or from_openid = '$openid' or to_openid = '$to' )" 
      ) )
        ->find ();
      if (empty ( $res )) {
        $ret = $MerWxChat->add ( array (
            "mer_id" => $mer_id,
            "from_openid" => $to,
            "to_openid" => $openid 
        ) );
        if ($ret) {
          return ajax_arr ( '连接建立成功，您可以关闭页面直接使用微信服务号给对方发送消息。', TRUE );
        } else {
          return ajax_arr ( '连接建立失败', FALSE );
        }
      } else {
        $ret = $MerWxChat->where ( "id = %d", $res ["id"] )
          ->save ( array (
            "from_openid" => $to,
            "to_openid" => $openid,
            "create_date" => date ( 'Y-m-d H:i:s' ) 
        ) );
        if ($ret) {
          return ajax_arr ( '连接建立成功，您可以关闭页面直接使用微信服务号给对方发送消息。', TRUE );
        } else {
          return ajax_arr ( '连接建立失败', FALSE );
        }
      }
    }
  }
  function find($mer_id, $from) {
    $MerWxChat = M ( 'MerWxChat' );
    $ret = $MerWxChat->where ( array (
        "mer_id" => $mer_id,
        '_query' => "from_openid=$from&to_openid=$from&_logic=or" 
    ) )
      ->find ();
    if (! empty ( $ret )) {
      $openid = $ret ["from_openid"] == $from ? $ret ["to_openid"] : $ret ["from_openid"];
      $MerUserOpenid = M ( 'MerUserOpenid' );
      $ret = $MerUserOpenid->where ( array (
          "openid" => $openid,
          "provider" => "wechat",
          "last_op_time" => array (
              'lt',
              date ( 'Y-m-d H:i:s', strtotime ( '+23 hour' ) ) 
          ) 
      ) )
        ->find ();
      if (! empty ( $ret )) {
        return $openid;
      }
    }
  }
}
